﻿using System;
using System.Reflection;
using BepInEx;
using Fortune.Context;
using Fortune.Exporter;
using Fortune.Loader;
using Fortune.Log;
using HarmonyLib;
using static Fortune.Configuration.FortuneConfiguration;

namespace Fortune
{
    [BepInPlugin(GUID, NAME, VERSION)]
    [BepInProcess(PROCESS_NAME)]
    public class FortuneApplication : BaseUnityPlugin
    {
        private static readonly FortuneLogger logger = FortuneLogger.newInstance(typeof(FortuneApplication));

        private void Start()
        {
            logger.info($"{NAME}.{VERSION} - {GUID} on {PROCESS_NAME}");
            Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly());
        }
        
        /// <summary>
        /// 造化玉碟初始化
        /// </summary>
        [HarmonyPatch(typeof(GameMain), "Begin")]
        public static class Init
        {
            [HarmonyPostfix]
            public static void postfix()
            {
                if (FortuneContext.isInitialized)
                {
                    logger.info("造化玉蝶已经启动，无需重复启动");
                    return;
                }
                logger.info("造化玉蝶开始加载");
                try
                {
                    // 加载BepInEx配置文件
                    BepInExConfigLoader.load();
                    // 初始化数据库
                    DatabaseInitLoader.load();
                    // 加载ORM框架FreeSQL
                    FreeSQLoader.load();
                    // 启动WebSocket服务，注册API
                    WebSocketAPILoader.load();
                }
                catch (Exception e)
                {
                    logger.error("造化玉蝶加载失败", e);
                    return;
                }
                logger.info("造化玉蝶加载成功");
                FortuneContext.startFortuneApplication();
                
                IconExporter.dumpItemIcon();
                IconExporter.dumpRecipeIcon();
                IconExporter.dumpTechIcon();
                IconExporter.dumpVeinIcon();
                IconExporter.dumpAchievementIcon();
                // IconExporter.dumpMilestoneIcon();
            }
        }
        
        /// <summary>
        /// 游戏结束时停止WebSocket服务
        /// </summary>
        [HarmonyPatch(typeof(UIRunner), "HandleApplicationQuit")]
        public static class ShutDown
        {
            [HarmonyPostfix]
            public static void postfix()
            {
                FortuneContext.webSocketServer.Stop();
            }
        }
    }
}